package com.bh.web.controller.system;

import cn.hutool.core.util.ReUtil;
import com.bh.common.annotation.Log;
import com.bh.common.constant.Constants;
import com.bh.common.core.controller.BaseController;
import com.bh.common.core.domain.AjaxResult;
import com.bh.common.core.domain.entity.SysDept;
import com.bh.common.core.domain.entity.SysRole;
import com.bh.common.core.domain.entity.SysUser;
import com.bh.common.core.page.TableDataInfo;
import com.bh.common.enums.BusinessType;
import com.bh.common.utils.SecurityUtils;
import com.bh.common.utils.StringUtils;
import com.bh.common.utils.poi.ExcelUtil;
import com.bh.kysys.domain.JcSysUserOrganization;
import com.bh.kysys.service.IJcSysUserOrganizationService;
import com.bh.kysys.vo.JcSysUserOrganizationVo;
import com.bh.system.service.ISysDeptService;
import com.bh.system.service.ISysPostService;
import com.bh.system.service.ISysRoleService;
import com.bh.system.service.ISysUserService;
import com.bh.vehicle.domain.JcDriver;
import com.bh.vehicle.service.IJcDriverService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author ruo-yi
 */
@Transactional(rollbackFor = Exception.class)
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private IJcDriverService driverService;

    @Autowired
    private IJcSysUserOrganizationService jcSysUserOrganizationService;

    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user) {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user) {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping({"/", "/{userId}"})
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        userService.checkUserDataScope(userId);
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId)) {
            SysUser sysUser = userService.selectUserById(userId);
            ajax.put(AjaxResult.DATA_TAG, sysUser);
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user) {
        if (!userService.checkUserNameUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        // 检测密码复杂度，必须为 6-20位，且包含字母、数字、符号
        if (!ReUtil.isMatch(Constants.REGEXP, user.getPassword())) {
            return error("密码必须包含大写字母 、数字、 特殊字符（四种里至少三种，且至少6位）");
        }
        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        // 如果是司机，则需要新增司机 （ 106L 代表司机）
        int num = userService.insertUser(user);
        // 需要添加组织人员
        SysDept dept = deptService.selectDeptById(user.getDeptId());
        if (dept != null && Objects.equals(dept.getIsOrg(), "Y")) {
            JcSysUserOrganization sysUserOrganization = new JcSysUserOrganization();
            sysUserOrganization.setUserId(user.getUserId());
            sysUserOrganization.setJcSysOrganizationId(user.getDeptId());
            jcSysUserOrganizationService.insert(sysUserOrganization);
        }
        // 如果是司机，则需要新增司机，存在两种司机角色
        boolean driverFlag = num > 0 && StringUtils.isNotEmpty(user.getRoleIds()) && user.getRoleIds().length > 0 && (ArrayUtils.contains(user.getRoleIds(), 106L) || ArrayUtils.contains(user.getRoleIds(), 111L));
        if (driverFlag) {
            JcDriver jcDriver = new JcDriver();
            jcDriver.setId(user.getUserId());
            jcDriver.setUserId(user.getUserId().toString());
            jcDriver.setIphone1(user.getPhonenumber());
            jcDriver.setSex(user.getSex());
            jcDriver.setJcOrganizationId(getOrgId());
            jcDriver.setName(user.getNickName());
            jcDriver.setCode(user.getUserName());
            driverService.saveOrUpdateJcDriver(jcDriver);
        }
        return toAjax(num);
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        if (!userService.checkUserNameUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        user.setUpdateBy(getUsername());
        int num = userService.updateUser(user);
        // ArrayUtils.contains 类型必须一致
        boolean driverFlag = num > 0 && StringUtils.isNotEmpty(user.getRoleIds()) && user.getRoleIds().length > 0 && (ArrayUtils.contains(user.getRoleIds(), 106L) || ArrayUtils.contains(user.getRoleIds(), 111L));
        if (driverFlag) {
            JcDriver jcDriver = new JcDriver();
            jcDriver.setId(user.getUserId());
            jcDriver.setUserId(user.getUserId().toString());
            jcDriver.setIphone1(user.getPhonenumber());
            jcDriver.setSex(user.getSex());
            jcDriver.setJcOrganizationId(getOrgId());
            jcDriver.setName(user.getNickName());
            jcDriver.setCode(user.getUserName());
            driverService.saveOrUpdateJcDriver(jcDriver);
        }
        return toAjax(num);
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        if (ArrayUtils.contains(userIds, getUserId())) {
            return error("当前用户不能删除");
        }
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user) {
        // 检测密码复杂度，必须为 6-20位，且包含字母、数字、符号
        if (!ReUtil.isMatch(Constants.REGEXP, user.getPassword())) {
            return error("密码必须包含大写字母 、数字、 特殊字符（四种里至少三种，且至少6位）");
        }
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        SysUser sysUser = userService.selectUserById(user.getUserId());
        sysUser.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        sysUser.setUpdateBy(getUsername());
        return toAjax(userService.resetPwd(sysUser));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping("/authRole/{userId}")
    public AjaxResult authRole(@PathVariable("userId") Long userId) {
        AjaxResult ajax = AjaxResult.success();
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }

    /**
     * 用户授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds) {
        userService.checkUserDataScope(userId);
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    /**
     * 获取部门树列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/deptTree")
    public AjaxResult deptTree(SysDept dept) {
        return success(deptService.selectDeptTreeList(dept));
    }


    @PreAuthorize("@ss.hasPermi('system:user:org')")
    @Log(title = "增加用户所属网点", businessType = BusinessType.UPDATE)
    @PostMapping("/batchAddOrg")
    public AjaxResult batchAddOrg(JcSysUserOrganizationVo organization) {
        if (organization.getOrganizationIds() == null || organization.getOrganizationIds().length == 0) {
            return error("请选择网点,或使用删除按钮删除！");
        }
        return toAjax(jcSysUserOrganizationService.batchAddOrg(organization));
    }


    @PreAuthorize("@ss.hasPermi('system:user:org')")
    @Log(title = "删除用户所属网点", businessType = BusinessType.DELETE)
    @DeleteMapping("/deleteUserOrg")
    public AjaxResult deleteUserOrg(JcSysUserOrganization organization) {
        return toAjax(jcSysUserOrganizationService.deleteUserOrg(organization));
    }
}
